﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class SiteMaster : MasterPage
{
  private const string AntiXsrfTokenKey = "__AntiXsrfToken";
  private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
  private string _antiXsrfTokenValue;

  protected void Page_Init(object sender, EventArgs e)
  {
    // 下面的程式碼有助於防禦 XSRF 攻擊
    var requestCookie = Request.Cookies[AntiXsrfTokenKey];
    Guid requestCookieGuidValue;
    if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
    {
      // 使用 Cookie 中的 Anti-XSRF 權杖
      _antiXsrfTokenValue = requestCookie.Value;
      Page.ViewStateUserKey = _antiXsrfTokenValue;
    }
    else
    {
      // 產生新的 Anti-XSRF 權杖並儲存到 cookie
      _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
      Page.ViewStateUserKey = _antiXsrfTokenValue;

      var responseCookie = new HttpCookie(AntiXsrfTokenKey)
      {
        HttpOnly = true,
        Value = _antiXsrfTokenValue
      };
      if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
      {
        responseCookie.Secure = true;
      }
      Response.Cookies.Set(responseCookie);
    }

    Page.PreLoad += master_Page_PreLoad;
  }

  void master_Page_PreLoad(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      // 設定 Anti-XSRF 權杖
      ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
      ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
    }
    else
    {
      // 驗證 Anti-XSRF 權杖
      if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
          || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
      {
        throw new InvalidOperationException("Anti-XSRF 權杖驗證失敗。");
      }
    }

    //取得登入使用者
    lblUserID.Text = Context.User.Identity.Name;
    if (!string.IsNullOrEmpty(lblUserID.Text))
    {
      using (MISEntities dc = new MISEntities())
      {
        var user = dc.MIS_USER_AP.Where(u => u.USER_ID == Context.User.Identity.Name).SingleOrDefault();
        if (user!=null)
        {
          lblUserID.Text = user.USER_NAME.Trim() + "[" + user.USER_ID + "]";
          var dept = dc.MIS_DEPT_AP.Where(d => d.DEPT_ID == user.DEPT_ID).SingleOrDefault();
          if (dept != null)
          {
            lbl_deptid.Text = dept.DEPT_ID.Trim();
            lblDept.Text = dept.DEPT_NAME.Trim();
          }          
        }
        
      }
    }

    //設定語系至控制項
    lbl_Language.Text =
            Request.Cookies["KerryLang"] != null ? Request.Cookies["KerryLang"].Values["Language"].ToString() : "zh-TW";
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(lbl_Language.Text);
    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lbl_Language.Text);
  }

  protected override void OnInit(EventArgs e)
  {
    base.OnInit(e);
    //使用blockUI，有下載功能的網頁無法運作
    string pagepath = Page.AppRelativeVirtualPath.ToLower();
    if (!pagepath.Contains("/system/") &&
        !pagepath.Contains("krj_document_download.aspx") && 
        !pagepath.Contains("announcementdetail.aspx"))
    {
      string imgUrl = Page.ResolveUrl("~/Images/Loading.gif");
      string sScript = "if (typeof(ValidatorOnSubmit) == \"function\" && ValidatorOnSubmit() == false) return false;";
      sScript += "$.blockUI({message: '<H1><Img Src=\"" + imgUrl + "\"/><br/>Data Processing...</H1>' , css: {border: 'none' , backgroundColor: 'none'} , overlayCSS: { backgroundColor: '#fff' } })";
      ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "blockUI", sScript);
      sScript = "$.unblockUI();";
      ScriptManager.RegisterStartupScript(this, this.GetType(), "unblockUI", sScript, true);
    }
  }

  protected void Page_PreRenderComplete(object sender, EventArgs e)
  {
    //使用blockUI，有下載功能的網頁無法運作
    //string pagepath = Page.AppRelativeVirtualPath.ToLower();
    //if (!pagepath.Contains("/system/") && !pagepath.Contains("krj_document_download.aspx"))
    //{
    //    string sScript = "$.unblockUI();";
    //    ScriptManager.RegisterStartupScript(this, this.GetType(), "unblockUI", sScript, true);
    //}
  }

  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      MenuUtil menu = new MenuUtil(NavigationMenu);
      //menu.BuildMenu(null); //未授權選單
      menu.BuildMenuByUser(null); //根據使用者授權選單
    }
  }
  protected void NavigationMenu_MenuItemClick(object sender, MenuEventArgs e)
  {
    try
    {
      using (MISEntities dc = new MISEntities())
      {
        MIS_FUNCTION_USER_LOG function_log = new MIS_FUNCTION_USER_LOG();
        function_log.USER_ID = Context.User.Identity.Name;
        function_log.FUNCTION_ID = e.Item.Value;
        function_log.LOGIN_DATE = DateTime.Now.ToString("yyyyMMdd");
        function_log.LOGIN_TIME = DateTime.Now.ToString("hhmmss");
        function_log.DEPT_ID = lbl_deptid.Text;
        function_log.CRT_ID = Context.User.Identity.Name;
        function_log.CRT_DATE = DateTime.Now.ToString("yyyyMMdd");
        function_log.CRT_TIME = DateTime.Now.ToString("hhmmss");
        function_log.UPD_ID = Context.User.Identity.Name;
        function_log.UPD_DATE = DateTime.Now.ToString("yyyyMMdd");
        function_log.UPD_TIME = DateTime.Now.ToString("hhmmss");
        dc.MIS_FUNCTION_USER_LOG.Add(function_log);
        dc.SaveChanges();
        string path = dc.MIS_FUNCTION_AP.Where(f => f.FUNCTION_ID == e.Item.Value).Single().FUNCTION_PATH;
        if (!string.IsNullOrEmpty(path))
        {
          Response.Redirect(path);
        }
      }
    }
    catch (Exception ex)
    {
      throw ex;
    }

  }
  protected void lb_signout_Click(object sender, EventArgs e)
  {
    System.Web.Security.FormsAuthentication.SignOut();
    Response.Redirect("~/Login.aspx");
  }
  protected void lb_help_Click(object sender, EventArgs e)
  {

  }
  protected void lb_print_Click(object sender, EventArgs e)
  {

  }
}